package com.aiton.bamin.bamindaijiadrier.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.Installation;
import com.aiton.administrator.shane_library.shane.utils.IsMobileNOorPassword;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.aiton.administrator.shane_library.shane.widget.WheelView;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.Sms;
import com.aiton.bamin.bamindaijiadrier.model.UserStatus;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.utils.EncryptUtils;
import com.igexin.sdk.PushManager;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;

import cn.qqtheme.framework.picker.AddressPicker;
import cn.qqtheme.framework.util.ConvertUtils;
import cz.msebera.android.httpclient.Header;

public class ApplyActivity extends ZjbBaseActivity implements View.OnClickListener {

    private EditText mEdt_name;
    private EditText mEdt_phone;
    //    private EditText mEdt_sms;
    private EditText mEdi_cardId;
    private EditText mEdt_drivingId;
    private EditText mEdt_emergency;
    private Button mBtn_next;
    //    private Button mBtn_sendSms;
    private String mPhone;
    private int[] mI;
    private Runnable mR;
    private String mSuijiMath;
    private EditText mEdt_drivingTime;
    private WheelView mWv_year;
    private WheelView mWv_month;
    private TextView mTv_year;
    private TextView mTv_month;
    private View mBtn_sure;
    private View mBtn_cancel;
    private String[] yearArray;
    private String[] monthArray;
    private int sex = 1;
    private int yearIndex;
    private int monthIndex;
    private ImageView mMan;
    private ImageView mWoman;
    private EditText mEdt_drivingCity;
    private EditText mEdt_password;
    private EditText mEdt_sms;
    private Button mBtn_sendSms;
    private EditText mEdt_password_again;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply);
        init();
    }

    @Override
    protected void initData() {
        /*
        获取驾照时间
         */
        yearArray = getResources().getStringArray(R.array.year);
        monthArray = getResources().getStringArray(R.array.month);
        yearIndex = yearArray.length - 1;
        monthIndex = monthArray.length - 1;
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_back).setOnClickListener(this);
        mBtn_sendSms.setOnClickListener(this);
        mBtn_next.setOnClickListener(this);
        mEdt_phone.addTextChangedListener(new MyPhoneTextWatcher());
        mMan.setOnClickListener(this);
        mWoman.setOnClickListener(this);
        mEdt_drivingCity.setOnClickListener(this);
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {

    }

    class MyPhoneTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (mEdt_phone.getText().length() != 11) {
                mBtn_sendSms.setEnabled(false);
            } else {
                mBtn_sendSms.setEnabled(true);

            }
        }
    }

    @Override
    protected void findID() {
        mEdt_name = (EditText) findViewById(R.id.edt_name);
        mEdt_phone = (EditText) findViewById(R.id.edt_phone);
        mEdt_sms = (EditText) findViewById(R.id.edt_sms);
        mEdi_cardId = (EditText) findViewById(R.id.edt_cardId);

        mEdt_emergency = (EditText) findViewById(R.id.edt_emergency);
        mEdt_drivingCity = (EditText) findViewById(R.id.edt_drivingCity);
        mEdt_password = (EditText) findViewById(R.id.edt_password);
        mEdt_password_again = (EditText) findViewById(R.id.edt_password_again);
        mBtn_next = (Button) findViewById(R.id.btn_next);
        mMan = (ImageView) findViewById(R.id.man);
        mWoman = (ImageView) findViewById(R.id.woman);
        mBtn_sendSms = (Button) findViewById(R.id.btn_sendSms);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.btn_sendSms:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS},
                            Constant.PERMISSION.PERMISSION_READ_SMS);
                } else {
                    if (IsMobileNOorPassword.isMobileNO(mEdt_phone.getText().toString().trim())) {
                        sendSMS();
                    } else {
                        mEdt_phone.setError("输入手机格式错误");
                    }
                }
                break;
            case R.id.btn_next://下一步
                if (!IsMobileNOorPassword.checkChineseName(mEdt_name.getText().toString().trim())) {
                    mEdt_name.setError("请输入正确的姓名");
                } else if (!IsMobileNOorPassword.isMobileNO(mEdt_phone.getText().toString().trim())) {
                    mEdt_phone.setError("请输入正确的手机号");
                } else if (TextUtils.isEmpty(mEdt_sms.getText().toString())) {
                    mEdt_sms.setError("验证码不能为空");
                } else if (TextUtils.isEmpty(mEdt_drivingCity.getText().toString().trim())) {
                    mEdt_drivingCity.setError("请选择城市");
                } else if (!(mEdi_cardId.getText().length() == 15 || mEdi_cardId.getText().length() == 18)) {
                    mEdi_cardId.setError("请输入正确的身份证号");
                }else if (!IsMobileNOorPassword.isPassword(mEdt_password.getText().toString().trim())) {
                    mEdt_password.setError("密码必须大于等于6位，且由字母及数字组合");
                } else if (!mEdt_password_again.getText().toString().trim().equals(mEdt_password.getText().toString().trim())) {
                    mEdt_password_again.setError("两次输入密码不一样");
                } else if (!IsMobileNOorPassword.isMobileNO(mEdt_emergency.getText().toString().trim())) {
                    mEdt_emergency.setError("请输入正确的手机号");
                } else {
                    applyNext();
                }
//                applyNext();
                break;

            case R.id.edt_drivingCity://选择城市
                showAddressChoose();
                break;
            case R.id.man:
                mMan.setImageResource(R.mipmap.btn_man_selected);
                mWoman.setImageResource(R.mipmap.btn_woman_normal);
                sex = 1;
                break;
            case R.id.woman:
                mMan.setImageResource(R.mipmap.btn_man_normal);
                mWoman.setImageResource(R.mipmap.btn_woman_selected);
                sex = 0;
                break;
        }
    }

    /**
     * 注册
     */
    private void applyNext() {
        final String DeviceId = Installation.id(this);
        final String Sms = mEdt_sms.getText().toString().trim();
        String password = mEdt_password.getText().toString().trim();
        String password4Encrypt = EncryptUtils.encryptSHA256ToString(password);
        if (Sms.equals("8888") || mSuijiMath.equals(Sms)) {
            String url = Constant.Url.REGISTERDRIVER;
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            showLoadingDialog(asyncHttpClient,this);
            RequestParams params = new RequestParams();
            params.put("name",mEdt_name.getText().toString().trim());
            params.put("phone",mEdt_phone.getText().toString().trim());
            params.put("sex",sex);
            params.put("serviceCity",mEdt_drivingCity.getText().toString().trim());
            params.put("cardId",mEdi_cardId.getText().toString().trim());
            params.put("password", password4Encrypt);
            params.put("urgentPhone",mEdt_emergency.getText().toString().trim());
            params.put("key", PushManager.getInstance().getClientid(this));
            params.put("deviceid", DeviceId + "");
            Log.e("ApplyActivity", "name: --->>" +mEdt_name.getText().toString().trim() );
            Log.e("ApplyActivity", "phone: --->>" +mEdt_phone.getText().toString().trim() );
            Log.e("ApplyActivity", "sex: --->>" + sex);
            Log.e("ApplyActivity", "serviceCity: --->>" + mEdt_drivingCity.getText().toString().trim());
            Log.e("ApplyActivity", "cardId: --->>" + mEdi_cardId.getText().toString().trim());
            Log.e("ApplyActivity", "password: --->>" + password4Encrypt);
            Log.e("ApplyActivity", "urgentPhone: --->>" +mEdt_emergency.getText().toString().trim() );
            Log.e("ApplyActivity", "key: --->>" +PushManager.getInstance().getClientid(this) );
            Log.e("ApplyActivity", "deviceid: --->>" +DeviceId );

            asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String s = new String(responseBody);
                    try {
                        Log.e("ApplyActivity", "onSuccess: --->>" +s );
                        UserStatus userStatus = GsonUtils.parseJSON(s, UserStatus.class);
                        if(userStatus.getStatus() == 0){
                            showSuccessSingleDialog(userStatus.getMes(), "确定");
                        }else{
                            showSingleDialog(userStatus.getMes(), "确定");
                        }

                        cancelLoadingDialog();

                    } catch (Exception e) {
                        cancelLoadingDialog();

                        showSingleDialog("提交失败，解析出错", "确定");

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    cancelLoadingDialog();
                    showSingleDialog("提交失败，服务器出错", "确定");

                }
            });
        } else {
            Toast.makeText(ApplyActivity.this, "验证码不正确", Toast.LENGTH_SHORT).show();
        }
//        Intent intent = new Intent(this, ApplyPictureActivity.class);
//        intent.putExtra(Constant.INTENT_KEY.USER_NAME, mEdt_name.getText().toString().trim());
//        intent.putExtra(Constant.INTENT_KEY.USER_PHONE, mEdt_phone.getText().toString().trim());
//        intent.putExtra(Constant.INTENT_KEY.SEX, sex);
//        intent.putExtra(Constant.INTENT_KEY.USER_DRIVING_CITY, mEdt_drivingCity.getText().toString().trim());
//        intent.putExtra(Constant.INTENT_KEY.USER_CARD_ID, mEdi_cardId.getText().toString().trim());
////        intent.putExtra(Constant.INTENT_KEY.USER_DRIVING_ID, mEdt_drivingId.getText().toString().trim());
////        intent.putExtra(Constant.INTENT_KEY.USER_DRIVING_TIME, mEdt_drivingTime.getText().toString().trim());
//        intent.putExtra(Constant.INTENT_KEY.USER_EMERGENCY, mEdt_emergency.getText().toString().trim());
//        startActivityTo(intent);


    }
    private void showSuccessSingleDialog(String title, String confirm) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, title, confirm);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
                finishTo();
            }
        });
        singleBtnDialog.show();
    }
    private void showSingleDialog(String title, String confirm) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, title, confirm);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
            }
        });
        singleBtnDialog.show();
    }

    /**
     * 地址选择器
     */
    private void showAddressChoose() {
        try {
            ArrayList<AddressPicker.Province> data = new ArrayList<AddressPicker.Province>();
            String json = ConvertUtils.toString(getAssets().open("city.json"));
            data.addAll(JSON.parseArray(json, AddressPicker.Province.class));
            AddressPicker picker = new AddressPicker(this, data);
            picker.setHideCounty(true);

            picker.setSelectedItem("福建", "厦门");
            picker.setOnAddressPickListener(new AddressPicker.OnAddressPickListener() {
                @Override
                public void onAddressPicked(AddressPicker.Province province, AddressPicker.City city, AddressPicker.County county) {
                    if (county == null) {
                        mEdt_drivingCity.setText(province.getAreaName() + "  " + city.getAreaName());

                    } else {
                        mEdt_drivingCity.setText(province.getAreaName() + "  " + city.getAreaName() + "  " + county.getAreaName());

                    }
                }
            });
            picker.show();
        } catch (Exception e) {
            Toast.makeText(this, "出错了", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 发送短信
     */
    private void sendSMS() {
        mPhone = mEdt_phone.getText().toString().trim();
        boolean mobileNO = IsMobileNOorPassword.isMobileNO(mPhone);
        if (mobileNO) {
            mBtn_sendSms.setEnabled(false);
            mI = new int[]{60};

            mR = new Runnable() {
                @Override
                public void run() {
                    mBtn_sendSms.setText((mI[0]--) + "秒后重发");
                    if (mI[0] == 0) {
                        mBtn_sendSms.setEnabled(true);
                        mBtn_sendSms.setText("验证");
                        return;
                    } else {
                    }
                    mBtn_sendSms.postDelayed(mR, 1000);
                }
            };
            mBtn_sendSms.postDelayed(mR, 0);
            getSms();
        } else {
            Toast.makeText(this, "输入的手机格式有误", Toast.LENGTH_SHORT).show();
            mEdt_phone.setText("");
        }
    }

    private void getSms() {
        mSuijiMath = (int) (Math.random() * 9000 + 1000) + "";
        String url = Constant.Url.GET_SMS;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("phone", mEdt_phone.getText().toString().trim());
        params.put("code", mSuijiMath + "");
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                try {
                    Sms sms = GsonUtils.parseJSON(s, Sms.class);
                    int status = sms.getStatus();
                    Toast.makeText(ApplyActivity.this, sms.getMes(), Toast.LENGTH_SHORT).show();
                    if (status == 0) {
                        //短信发送成功
                    } else if (status == 1) {
                        //短信发送失败
                    }
                } catch (Exception e) {
                    Toast.makeText(ApplyActivity.this, "服务器出错", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(ApplyActivity.this, "短信发送失败", Toast.LENGTH_SHORT).show();

            }
        });
    }
}
